// audioManager.js
class AudioManager {
  constructor() {
    this.audioPool = {}; // 用于存储音频实例，key 为音频的唯一标识
    this.audioSources = {
      // 统一管理音频素材地址
      jiaozai: 'https://level-huang.oss-cn-chengdu.aliyuncs.com/audio/guochang.wav',
	  daoting:"https://level-huang.oss-cn-chengdu.aliyuncs.com/audio/dating.mp3",
	  qiangsheng:"https://level-huang.oss-cn-chengdu.aliyuncs.com/audio/qiangsheng_bgm.wav",
     
      // 可以继续添加更多音频
    };
  }

  /**
   * 获取音频素材地址
   * @param {string} audioId 音频的唯一标识
   * @returns {string|null} 音频文件路径，如果未找到则返回 null
   */
  getAudioSource(audioId) {
    return this.audioSources[audioId] || null;
  }

  /**
   * 创建或获取音频实例
   * @param {string} audioId 音频的唯一标识
   * @returns {Object} InnerAudioContext 实例
   */
  getOrCreateAudio(audioId) {
    if (!this.audioPool[audioId]) {
      const audioContext = uni.createInnerAudioContext();
      audioContext.onPlay(() => {
        console.log(`Audio ${audioId} is playing`);
      });
      audioContext.onPause(() => {
        console.log(`Audio ${audioId} is paused`);
      });
      audioContext.onStop(() => {
        console.log(`Audio ${audioId} is stopped`);
      });
      audioContext.onEnded(() => {
        console.log(`Audio ${audioId} has ended`);
      });
      audioContext.onError((res) => {
        console.error(`Audio ${audioId} error:`, res);
      });
      this.audioPool[audioId] = audioContext;
    }
    return this.audioPool[audioId];
  }

  /**
   * 播放音频
   * @param {string} audioId 音频的唯一标识
   * @param {boolean} loop 是否循环播放
   */
  playAudio(audioId, loop = false) {
    const src = this.getAudioSource(audioId);
    if (!src) {
      console.error(`Audio source for ${audioId} not found`);
      return;
    }
    const audioContext = this.getOrCreateAudio(audioId);
    audioContext.src = src;
    audioContext.loop = loop;
    audioContext.play();
  }

  /**
   * 暂停音频
   * @param {string} audioId 音频的唯一标识
   */
  pauseAudio(audioId) {
    const audioContext = this.audioPool[audioId];
    if (audioContext) {
      audioContext.pause();
    } else {
      console.warn(`Audio ${audioId} not found`);
    }
  }

  /**
   * 停止音频
   * @param {string} audioId 音频的唯一标识
   */
  stopAudio(audioId) {
    const audioContext = this.audioPool[audioId];
    if (audioContext) {
      audioContext.stop();
    } else {
      console.warn(`Audio ${audioId} not found`);
    }
  }

  /**
   * 销毁音频实例
   * @param {string} audioId 音频的唯一标识
   */
  destroyAudio(audioId) {
    const audioContext = this.audioPool[audioId];
    if (audioContext) {
      audioContext.destroy();
      delete this.audioPool[audioId];
    } else {
      console.warn(`Audio ${audioId} not found`);
    }
  }

  /**
   * 停止并销毁所有音频实例
   */
  destroyAll() {
    Object.keys(this.audioPool).forEach((audioId) => {
      this.destroyAudio(audioId);
    });
  }
}

// 导出单例实例
const audioManager = new AudioManager();
export default audioManager;